package club.pinea.loader;

import club.pinea.annotations.Head;
import club.pinea.interfaces.TCPMessage;
import club.pinea.utils.SpringContextUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component("commandLoader")
public class CommandLoader {

    private final String BASE_PACKAGE = "club.pinea.handler";
    private final String RESOURCE_PATTERN = "/**/*.class";

    private Map<Integer, TCPMessage<?>> handlerMap = new ConcurrentHashMap<>();

    /**
     * 加载command对应的处理类
     */
    public void loadCommand() {

        //spring工具类，可以获取指定路径下的全部类
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        try {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE) + RESOURCE_PATTERN;
            Resource[] resources = resourcePatternResolver.getResources(pattern);
            //MetadataReader 的工厂类
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : resources) {
                //用于读取类信息
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                //扫描到的class
                String classname = reader.getClassMetadata().getClassName();
                Class<?> clazz = Class.forName(classname);
                //判断是否有指定主解
                Head anno = clazz.getAnnotation(Head.class);
                if (anno != null) {
                    //将注解中的类型值作为key，对应的类作为 value
//                    handlerMap.put(classname, clazz);
                    Object bean = SpringContextUtils.getBean(clazz);
                    if (bean instanceof TCPMessage) {
                        TCPMessage<?> tcpMessage = (TCPMessage<?>) bean;
                        handlerMap.put(anno.value(), tcpMessage);
                    }
                }
            }
        } catch (IOException | ClassNotFoundException e) {
        }
    }

    /**
     * 获取处理类
     *
     * @param command
     * @return
     */
    public TCPMessage getHandler(int command) {
        return handlerMap.get(command);
    }


}
